<template>
	<view class="iconfont  min-btn"
		:class="{'icon-play':state=='stop','icon-pause':state=='play','icon-play':state=='pause'}" :style="innerStyle"
		@click="click"></view>
</template>
<script>
	export default {
		name: 'lmAudio',
		props: ['src', 'innerStyle'],
		emits: ['onPlay', 'onPause', 'onStop', 'onEnded'],
		data() {
			return {
				state: 'stop',
				audioContext: '',
				innerSrc: this.src,
				nowTime:0,
				allTime:0
			}
		},
		watch: {
			src(newValue, oldValue) {
				if (newValue != oldValue) {
					this.innerSrc = newValue;
					this.nowTime = this.audioContext.currentTime;
					this.allTime = this.audioContext.duration;
					uni.setStorageSync('allTime',this.audioContext.duration);
					console.log('currentTime',this.audioContext.currentTime)
					console.log('duration',JSON.stringify(this.audioContext.duration))
					this.initAudioContext();
				}
			}
		},
		methods: {
			click() {
				if ('stop,pause'.indexOf(this.state) != -1) {
					this.play();
				} else if (this.state == 'play') {
					this.pause();
				}
			},
			play() {
				// this.audioContext.src = this.innerSrc;
				this.audioContext.play();
			},
			pause() {
				this.audioContext.pause();
			},
			stop() {
				this.audioContext.stop();
			},
			initAudioContext() {
				const self = this;
				var audioContext = uni.createInnerAudioContext();
				// audioContext.autoplay = true;
				audioContext.src = this.innerSrc;
				audioContext.onPlay(function(res) {
					self.state = 'play';
					self.$emit('onPlay', res);
					console.log('lm',res)
				});
				audioContext.onPause(function(res) {
					self.state = 'pause';
					self.$emit('onPause', res);
				});
				audioContext.onStop(function(res) {
					self.state = 'stop';
					self.$emit('onStop', res);
				});
				audioContext.onEnded(function(res) {
					self.state = 'stop';
					self.$emit('onEnded', res);
				});
				audioContext.onError(function(res) {
					console.log(res)
				});
				this.audioContext = audioContext;

			}

		}
	}
</script>
<style>
	@import "./static/font/iconfont.css";

	.min-btn {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 5px;
		height: 5px;
		padding: 10px;
		background-color: #007aff;
		border-radius: 50px;
		/* border: 1px solid #c1c0c0; */
		font-size: 10px;
		color: #FFF;
	}
</style>